package com.ler.yrmall.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ler.yrmall.dto.LoginUser;
import com.ler.yrmall.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author leron
 */
@Configuration
@ConditionalOnClass(MybatisPlusInterceptor.class)
@MapperScan(basePackages = "com.ler.**.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                LoginUser loginUser = getLoginUser();
                this.setFieldValByName("createBy", loginUser.getUsername(), metaObject);
                this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                LoginUser loginUser = getLoginUser();
                this.setFieldValByName("updateBy", loginUser.getUsername(), metaObject);
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
        };
    }

    private LoginUser getLoginUser() {
        LoginUser loginUser;
        try {
            loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                loginUser = new LoginUser();
                loginUser.setUsername("-1");
            }
        } catch (Exception e) {
            loginUser = new LoginUser();
            loginUser.setUsername("-1");
        }
        return loginUser;
    }
}
